package features.advance.sql.jsqlparser;

import net.sf.jsqlparser.parser.*;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;

/**
 * @author LIN
 * @date 2022-12-29 16:52
 */
public class JsqlparserDemo {

    public static void main(String[] args) throws ParseException {
        String sql = "SELECT person.id,person.name,group.name  FROM person JOIN group ON person.group_id = group.id WHERE person.birthdat > '1980-01-01'";
//        创建SQL语句解析器实例
        CCJSqlParser parser = CCJSqlParserUtil.newParser(sql);
//      解析SQL语句
        Statement statement = parser.Statement();
        parser.getASTRoot().jjtAccept(new LogVisitor(),null);
        System.out.printf("sql--> %s",statement);
    }
    /**
     * 遍历所有节点的{@link net.sf.jsqlparser.parser.CCJSqlParserVisitor} 接口实现类
     * @author guyadong
     *
     */
    static class LogVisitor extends CCJSqlParserDefaultVisitor{
        @Override
        public Object visit(SimpleNode node, Object data) {
            Object value = node.jjtGetValue();
            /** 根据节点类型找出表名和字段名节点，对名字加上双引号 */
            if (node.getId() == CCJSqlParserTreeConstants.JJTCOLUMN) {
                System.out.printf("column %s",value.toString());
                Column column = (Column)value;
                column.setColumnName("\"" + column.getColumnName() + "\"");
                Table table = column.getTable();
                if(null != table){
                    table.setName("\"" + table.getName() + "\"");
                }
            } else if (node.getId() == CCJSqlParserTreeConstants.JJTTABLE) {
                System.out.printf("table %s",value.toString());
                Table table = (Table)value;
                if(null != table){
                    table.setName("\"" + table.getName() + "\"");
                }
            }else if(null != value){
                /** 其他类型节点输出节点类型值，Java类型和节点值 */
                System.out.printf("%d %s %s",node.getId(),value.getClass().getSimpleName(),value.toString());
            }
            return super.visit(node, data);
        }
    }

}
